package com.ck.web.controller.login;

import com.ck.web.common.spring.SpringBeanNames;
import com.ck.web.common.spring.SpringContextHolder;
import com.ck.web.controller.base.BaseController;
import com.ck.web.model.base.BaseResponse;
import com.ck.web.shiro.LoginException;
import com.ck.web.shiro.LoginExceptionEnum;
import com.ck.web.shiro.LoginFormAuthenticationFilter;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录controller
 * Created by ChengK on 2016/12/23 0023.
 */
@Slf4j
@Controller
@RequestMapping(value = "/login")
public class LoginController extends BaseController{

    /**
     * 处理失败
     * 如果登录成功，跳转至首页；登录失败，则将失败信息反馈对用户
     */
    @RequestMapping(value = "/doLogin")
    public ModelMap login(HttpServletRequest request, HttpServletResponse response) throws IOException {
        BaseResponse<Boolean> baseResponse = new BaseResponse<>();
        log.debug("==========================进入失败处理controller=================================");
        String msg;
        String userName = request.getParameter("loginNo");
        String password = request.getParameter("password");

        UsernamePasswordToken token = new UsernamePasswordToken(userName, password);
        token.setRememberMe(true);

        // 验证用户已经登录
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            baseResponse.setError(LoginExceptionEnum.ALREADY_LOGIN_IN.getCode(),LoginExceptionEnum.ALREADY_LOGIN_IN.getDesc());
            return processSuccessJSON(baseResponse);
        }

        // 获取登入异常信息
        LoginFormAuthenticationFilter loginFormAuthenticationFilter = SpringContextHolder.getBean(SpringBeanNames.LoginFormAuthenticationFilter);
        if (loginFormAuthenticationFilter == null) {
            throw new RuntimeException("获取注入Bean失败，BeanName=" + SpringBeanNames.LoginFormAuthenticationFilter);
        }
        AuthenticationException authenticationException = (AuthenticationException) request.getAttribute(loginFormAuthenticationFilter.getFailureKeyAttribute());
        if (authenticationException == null) {
            throw new RuntimeException("获取登录异常信息失败");
        }
        if(authenticationException instanceof LoginException){
            LoginException loginException = (LoginException) authenticationException;
            baseResponse.setError(loginException.getErrorCode(),loginException.getMessage());
        }else{
            if(authenticationException instanceof IncorrectCredentialsException){
                msg = "登录密码错误. Password for account " + token.getPrincipal() + " was incorrect.";
                baseResponse.setError(LoginExceptionEnum.LOGIN_PWD_ERROR.getCode(),msg);
            } else if(authenticationException instanceof ExcessiveAttemptsException){
                msg = "登录失败次数过多";
                baseResponse.setError(LoginExceptionEnum.LOGIN_ERROR_TOO_MANY.getCode(),msg);
            } else if(authenticationException instanceof LockedAccountException){
                msg = "帐号已被锁定. The account for username " + token.getPrincipal() + " was locked.";
                baseResponse.setError(LoginExceptionEnum.ACCOUNT_WAS_LOCKED.getCode(),msg);
            } else if(authenticationException instanceof DisabledAccountException){
                msg = "帐号已被禁用. The account for username " + token.getPrincipal() + " was disabled.";
                baseResponse.setError(LoginExceptionEnum.ACCOUNT_WAS_DISABLED.getCode(),msg);
            } else if(authenticationException instanceof ExpiredCredentialsException){
                msg = "帐号已过期. the account for username " + token.getPrincipal() + "  was expired.";
                baseResponse.setError(LoginExceptionEnum.ACCOUNT_WAS_EXPIRED.getCode(),msg);
            } else if(authenticationException instanceof UnknownAccountException){
                msg = "帐号不存在. There is no user with username of " + token.getPrincipal();
                baseResponse.setError(LoginExceptionEnum.ACCOUNT_NOT_EXIST.getCode(),msg);
            } else{
                baseResponse.setError(LoginExceptionEnum.UNKNOWN_ERROR.getCode(),LoginExceptionEnum.UNKNOWN_ERROR.getDesc());
            }
        }
        return processSuccessJSON(baseResponse);
    }
}
